package com.test.work.common.config;

/**
 * @Description
 * @Author GL
 * @Date 2024/8/24
 */
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;

import java.util.ArrayList;
import java.util.List;

// 该类的目的是把自定义编写的转换类 注入 MongoTemplate 中
/*@Configuration*/
public class MongoConfig {

    //@Autowired
    MongoDatabaseFactory factory;

    //MongoCustomConversions
    @Bean //注册客制化转换 添加自定义转换类(楼主以TestConverter为列，具体编写跳转“编写自定义转换类”)
    public MongoCustomConversions customConversions() {

        List<Converter<?,?>> converters = new ArrayList<Converter<?,?>>();

        converters.add(new DateConverter());

        return new MongoCustomConversions(converters);
    }

    @Bean
    public MongoTemplate mongoTemplate() {

        MongoTemplate mongoTemplate = new MongoTemplate(factory);
        MappingMongoConverter mongoMapping = (MappingMongoConverter) mongoTemplate.getConverter();
        mongoMapping.setCustomConversions(customConversions()); // tell mongodb to use the custom converters
        mongoMapping.afterPropertiesSet();
        System.out.println("注入成功!");
        return mongoTemplate;

    }

}
